package com.pms.eap.manager;

import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Session;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.googlecode.cswish.annotation.ParamScope;
import com.googlecode.cswish.model.PageElements;
import com.googlecode.cswish.model.PageInfo;
import com.googlecode.cswish.model.Reference;
import com.googlecode.cswish.oosearch.QLInfo;
import com.googlecode.cswish.struts.conversion.PageElementService;
import com.googlecode.cswish.struts.spring.CacheService;
import com.googlecode.cswish.struts.spring.GenericService;

@Service
@Transactional
public class DepartmentService {

	@Resource
	GenericService genericService;
	
	@PersistenceContext(unitName="espirit")
	private EntityManager em;
	
	@Resource
	private PageElementService pageElementService;
	
	@Resource
	CacheService cacheService;
	
	Map<String , Integer> deptCache ;
	@PostConstruct
	private void init() {
		deptCache = cacheService.newCache(Integer.class);
	}
	
	public Department add(Department model){
		model = genericService.add(model);
		model.getParents().get(0).setPartyChild(model);
		genericService.update(model);
		return model;
	}
	
	@Transactional
    public boolean deleteList(List<Department> results) {
    	boolean ret = true;
    	if (results != null) {
			for (Department department : results) {
				if (department != null) {
					String hql = "delete from PartyRelationship a where a.partyChild.id =" + department.getId();
					((Session)em.getDelegate()).createQuery(hql).executeUpdate();

					ret &= genericService.delete(department);
				}
			}
    	}
    	return ret;
    }
	public PageInfo<Department> search(Department model, String keywords,
			int start, int limit, String sort, String dir, boolean newSearch,
			Reference<QLInfo> qlInfoRef, @ParamScope(visible=false, value="#ps")PageElements ps){
		if (newSearch) {
			PageElements psAdd = pageElementService.getPageElements(Department.class.getName(), "_add");
			psAdd.addExtraName("model.parents[0].partyParent.id", null, null);
			psAdd.addExtraName("model.name", null, null);
		}
		
		limit = 10000;
		PageInfo<Department> pageInfo = genericService.search(model, start, limit, sort, dir, newSearch, qlInfoRef);
		return pageInfo;
	}

	
	public Integer getDeptIdByName(String deptName) {
		if (deptName == null ) return null;
    	if (deptCache.get(deptName) == null){
    		Department search = new Department();
			search.setName(deptName);
			Department theDept = genericService.searchAll(search).getData(0);
			if (theDept == null){
				return null;
			}
			deptCache.put(deptName, theDept.getId());
    	}
    	return deptCache.get(deptName);
	}
	
}
